/**
 * 
 */
package com.suixun.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.authority.common.MD5Util;
import com.authority.common.UserTypeEnum;
import com.authority.controller.BaseManager;
import com.authority.utils.TokenUtils;
import com.google.gson.Gson;
import com.suixun.entity.RegionInfo;
import com.suixun.entity.School;
import com.suixun.entity.form.ParamForm;
import com.suixun.entity.page.PageModel;
import com.suixun.exception.OpServiceException;
import com.suixun.service.SchoolService;
import com.suixun.util.Constant;
import com.suixun.vo.SchoolVO;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/schoolManage")
public class SchoolManage extends BaseManager {
	@Resource
	private SchoolService schoolService;

	/**
	 * 查询所有的学校列表
	 * 
	 * @return
	 */

	@RequestMapping(value = "querySchool.json")
	@ResponseBody
	public Object querySchoolList(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			ParamForm paramForm = checkParam(param, ParamForm.class);
			if (getUserType(getUserId()) == UserTypeEnum.REGIONMAN.getType()) {
				paramForm.setOrgan(true);
				paramForm.setUserid(getUserId());
			}
			return success(schoolService.querySchoollist(paramForm));
		} catch (Exception e) {
			logger("SchoolManage querySchoolList:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 分页查询学校列表
	 * 
	 * @return
	 */

//	@RequestMapping(value = "querySchoolList.json")
	@ResponseBody
	public Object querySchoolListPage(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		ParamForm paramForm = null;
		try {
			if (param == null) {
				paramForm=new ParamForm();
			}else {
				paramForm = new Gson().fromJson(param, ParamForm.class);
			}
			return success(schoolService.querySchoollistPage(paramForm));
		} catch (Exception e) {
			logger("SchoolManage querySchoolListPage:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 分页查询学校列表(新接口,查询时加入学校类型)
	 * @param param 查询条件
	 * @param type 学校类型，1：和教育
	 * @return
	 */
	@RequestMapping(value = "querySchoolList.json")
    @ResponseBody
    public Object querySchoolListNew(String param,@RequestParam(value = "type", required = false)Integer type) {
	    boolean bln = checkRight();
        if (!bln) {
            return fail(Constant.Authority.CHECK_FALSE);
        }
        ParamForm paramForm = null;
        try {
            if (param == null) {
                paramForm=new ParamForm();
            }else {
                paramForm = new Gson().fromJson(param, ParamForm.class);
            }
            return success(schoolService.querySchoollistPage(paramForm, type));
        } catch (Exception e) {
            logger("SchoolManage querySchoolListNew:"+e.getMessage(),e);
            return fail(Constant.EXCEPTION.OPERATE_FAIL);
        }
    }
	
	/**
	 * <p>Title: querySchoolDiscount</p>
	 * <p> 功能描述:查询促销(微运营) </p>
	 * @param schoolid
	 * @return
	 */
	@RequestMapping(value = "noCheck_querySchoolDiscount.json")
	@ResponseBody
	public Object querySchoolDiscount(Integer schoolid) {
		try {
			if (schoolid == null) {
				return fail(Constant.EMPTY);
			}
			return success(schoolService.querySchoolDiscount(schoolid));
		} catch (Exception e) {
			logger("SchoolManage querySchoolListPage:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 查询公共的行政区域
	 * 
	 * @return
	 */

	@RequestMapping(value = "queryRegion.json")
	@ResponseBody
	public Object queryRegion(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			RegionInfo paramForm = checkParam(param, RegionInfo.class);
			if (getUserType(getUserId()) == UserTypeEnum.REGIONMAN.getType()) {
				paramForm.setUserid(getUserId());
			}
			return success(schoolService.queryRegion(paramForm));
		} catch (Exception e) {
			logger("SchoolManage queryRegion:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	/**
	 * 
	 * <p>Title: querySchoolRegion</p>
	 * <p> 功能描述:查询指定学校对应的省市区 </p>
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "querySchoolRegion.json")
	@ResponseBody
	public Object querySchoolRegion(String param) {
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if(com.suixun.util.StringUtil.isEmpty(paramForm.getDis())) {
				return fail(Constant.EMPTY);
			}
			return success(schoolService.querySchoolRegion(paramForm));
		} catch (Exception e) {
			logger("SchoolManage querySchoolRegion:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 新增学校
	 * 
	 * @return
	 */

	@RequestMapping(value = "addSchool.json")
	@ResponseBody
	public Object addSchool(String param,String schooltype) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			SchoolVO schoolinfo = new Gson().fromJson(param, SchoolVO.class);
			if (schoolinfo == null || StringUtil.isBlank(schoolinfo.getSchoolname()))
				return fail(Constant.School.SCHOOLNAME_IS_EMPTY);
			if( schoolinfo.getYijiaoid()== null ) {
				return fail(Constant.School.YIJIAOID_IS_EMPTY);
			}
			//先判断学校名称是否已存在
			ParamForm paramForm=new ParamForm();
			paramForm.setSchoolname(schoolinfo.getSchoolname());
			School school=schoolService.querySchoolByName(paramForm);
			if(school!=null && school.getId()!=null) {
				return fail(Constant.School.SCHOOLNAME_IS_EXIST);
			}
			String res = schoolService.addSchool(schoolinfo, this.getUserId(),schooltype);
			if(Constant.SUCCESS.equals(res)) {
				return success();
			}else {
				return fail(res);
			}
		} catch (Exception e) {
			if(e instanceof OpServiceException) {
				return fail(e.getMessage());
			}
			logger("SchoolManage addSchool:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 修改学校
	 * //schooltype学校类型，为1时表示是和教育学校
	 * @return
	 */

	@RequestMapping(value = "modifySchool.json")
	@ResponseBody
	public Object modifySchool(String param,String schooltype) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			SchoolVO schoolinfo = new Gson().fromJson(param, SchoolVO.class);
			if (schoolinfo == null || schoolinfo.getId()==null) {
				return fail(Constant.EMPTY);
			}
			//先判断学校名称是否已存在
			ParamForm paramForm=new ParamForm();
			paramForm.setSchoolname(schoolinfo.getSchoolname());
			School school=schoolService.querySchoolByName(paramForm);
			if(school!=null && school.getId()!=null && school.getId().intValue()!=schoolinfo.getId().intValue()) {
				return fail(Constant.School.SCHOOLNAME_IS_EXIST);
			}
			schoolinfo.setOperationerid(getUserId());
			schoolinfo.setOperatorName(getUsername());
			String res = schoolService.modifySchool(schoolinfo, this.getUserId(),schooltype);
			
			if(Constant.SUCCESS.equals(res)) {
				return success();
			}else {
				return fail(res);
			}
		} catch (Exception e) {
			logger("SchoolManage modifySchool:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * <p>Title: modifySchool</p>
	 * <p> 功能描述:修改促销（微运营） </p>
	 * @param starttime
	 * @param endtime
	 * @param price
	 * @param account
	 * @param password
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "noCheck_modifySchoolDiscount.json")
	@ResponseBody
	public Object modifySchoolDiscount(String starttime,String endtime,BigDecimal price,String account,String password,Integer id) {
			if (StringUtil.isBlank(account)) {
				return fail(Constant.Authority.CHECK_FALSE);
			}
			try{
				SchoolVO schoolinfo = new SchoolVO();
				schoolinfo.setStarttime(starttime);
				schoolinfo.setEndtime(endtime);
				schoolinfo.setPrice(price);
				schoolinfo.setAccount(account);
				schoolinfo.setPassword(password);
				schoolinfo.setId(id);
				Integer chechAccount = checkCount(schoolinfo.getAccount(), MD5Util.MD5(schoolinfo.getPassword()));
				if (chechAccount == null) {
					return fail(Constant.Authority.CHECK_FALSE);
				}else {
					String token = TokenUtils.generateToken(chechAccount.toString(), null, null);
					getRequest().getSession().setAttribute("token", token);
					schoolinfo.setOperationerid((long)chechAccount);
				}
				if (schoolinfo == null || schoolinfo.getId()==null) {
					return fail(Constant.EMPTY);
				}
				int res = schoolService.updateSchoolDiscount(schoolinfo);
				if (res == -1) {
					return fail(Constant.School.DISCOUNT_TIME_EMPTY);
				}else if (res == -2) {
					return fail(Constant.School.DISCOUNT_TIME_FALSE);
				}else {
					return success();
				}
		} catch (Exception e) {
			logger("SchoolManage modifySchool:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 删除学校
	 * 
	 * @return
	 */

	@RequestMapping(value = "deleteSchool")
	@ResponseBody
	public Object deleteSchool(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			if (paramForm == null || StringUtil.isBlank(paramForm.getSchoolid())) {
				return fail(Constant.EMPTY);
			}
			//先判断学校是不是还有未删除的学生，如果有，不能删除
			int studentsCount=schoolService.querySchoolStudentCounts(paramForm);
			if(studentsCount!=0) {
				return fail(Constant.School.SCHOOL_HAVE_STUDENTS);
			}
			int res = schoolService.delSchool(Integer.parseInt(paramForm.getSchoolid()));
			
			if(res>0) {
				return success();
			}else {
				return fail(Constant.OPERATE_FAIL);
			}
		} catch (Exception e) {
			logger("SchoolManage deleteSchool:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 导出excel，不做鉴权
	 * 
	 * @return
	 */

	@RequestMapping(value = "export_SchoolList")
	@ResponseBody
	public Object exportSchoolList(String param) {
		boolean bln = checkRight();
		if (!bln) {
			toRedirect(404);
		}
		if (param == null) {
			param="";
		}
		try {
			ParamForm paramForm = new Gson().fromJson(param, ParamForm.class);
			ArrayList<String> listParm = new ArrayList<String>();
			listParm.add(Constant.Excel.SCHOOLNAME);
			listParm.add(Constant.Excel.TIME_SETTING);
			listParm.add(Constant.Excel.YIJIAOID);
			listParm.add(Constant.Excel.ADDRESS);
			listParm.add(Constant.Excel.PROVINCE);
			listParm.add(Constant.Excel.CITY);
			listParm.add(Constant.Excel.TOWN);
			listParm.add(Constant.Excel.DISCOUNT_TIME);
			listParm.add(Constant.Excel.DISCOUNT_PRICE);
			
			List<List<String>> listValue=new LinkedList<List<String>>();
			//限制最多导出1万条数据，前端可以通过细化查询条件来多次导出
			//if(StringUtil.isBlank(paramForm.getPagecount()))
				paramForm.setPagecount(Constant.Excel.EXPORT_ROWS);
			PageModel<SchoolVO> page = schoolService.querySchoollistPage(paramForm);
			List<SchoolVO> list=page.getQueryresult();

			for (int m = 0; m < list.size(); m++) {
				List<String> value=new LinkedList<String>();
				SchoolVO school = list.get(m);
				value.add(school.getSchoolname());
				value.add(school.getShowtimesetting());
				value.add(school.getYijiaoid() == null ? null : String.valueOf(school.getYijiaoid()));
				value.add(school.getAddress());
				value.add(school.getProvince());
				value.add(school.getCity());
				value.add(school.getTown());
				value.add(school.getPrice() == null ? null : String.valueOf(school.getPrice()));
				if (school.getStarttime() != null ) {
					value.add(new StringBuilder().append(school.getStarttime())
										.append("至").append(school.getEndtime()).toString());
				}else {
					value.add(null);
				}
				listValue.add(value);
				school = null;
			}
			// 创建新的Excel 工作簿
			HSSFWorkbook workbook = exportDeviceList(Constant.Excel.SCHOOL_EXCEL,listParm,listValue);
			HttpServletResponse response=this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=schoollist.xls");
			workbook.write(this.getResponse().getOutputStream());

		} catch (Exception e) {
			logger("SchoolManage exportSchoolList:"+e.getMessage(),e);
			toRedirect(500);
		}
		return success();
	}
}
